package com.cloud.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.cloud.auth.entity.AuthUser;
import com.cloud.auth.manager.UserManager;
import com.cloud.auth.mapper.UserMapper;
import com.cloud.auth.mapper.entity.SystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Auther: zhangxun
 * @Date: 2020/8/7 14:37
 */
@Service
public class UserDetailService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserManager userManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StrUtil.isBlank(username)){
            throw new UsernameNotFoundException("用户名不能为空！");
        }

        SystemUser systemUser = userManager.findByName(username);
        if (BeanUtil.isEmpty(systemUser)){
            throw new UsernameNotFoundException("用户名不存在！");
        }

        String permissions = userManager.findUserPermissions(systemUser.getUsername());
        boolean notLocked = false;
        if (SystemUser.STATUS_VALID.equals(systemUser.getStatus())){
            notLocked = true;
        }

        AuthUser authUser = new AuthUser(
                systemUser.getUsername(),
                systemUser.getPassword(),
                true,
                true,
                true,
                notLocked,
                AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
        BeanUtil.copyProperties(systemUser,authUser);
        return authUser;
//        systemUser.setPassword(this.passwordEncoder.encode(systemUser.getPassword()));
//        return new User(username, user.getPassword(), user.isEnabled(),
//                user.isAccountNonExpired(), user.isCredentialsNonExpired(),
//                user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("user:add"));
    }
}